# 类/方法：Booter（保持当前实现，无需改动）
import os
from typing import Optional

# 将第5行的相对导入改为绝对导入
from utils.constants import BOOTER_SUFFIX as CON_BOOTER_SUFFIX, BOOTER_TMP_SUFFIX as CON_BOOTER_TMP_SUFFIX

from src.utils.parser import Parser


class Booter:
    """启动器，记录第一个表的UID"""
    # 后缀
    BOOTER_SUFFIX = CON_BOOTER_SUFFIX
    # 临时后缀
    BOOTER_TMP_SUFFIX = CON_BOOTER_TMP_SUFFIX
    
    def __init__(self, path: str):
        self.path = path
        self.file_path = path + self.BOOTER_SUFFIX
    
    @classmethod
    def create(cls, path: str) -> 'Booter':
        """创建新的booter文件"""
        cls._remove_bad_tmp(path)
        file_path = path + cls.BOOTER_SUFFIX

        if not os.path.exists(file_path):
            # 文件不存在时创建文件
            with open(file_path, 'wb') as f:
                f.write(b'\x00' * 8)  # 初始化为0

        return cls(path)
    
    @classmethod
    def open(cls, path: str) -> 'Booter':
        """打开已有的booter文件"""
        cls._remove_bad_tmp(path)
        file_path = path + cls.BOOTER_SUFFIX
        
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"Booter file not found: {file_path}")
        
        return cls(path)
    
    @classmethod
    def exists(cls, path: str) -> bool:
        """检查booter文件是否存在"""
        file_path = path + cls.BOOTER_SUFFIX
        return os.path.exists(file_path)
    
    @staticmethod
    def _remove_bad_tmp(path: str) -> None:
        """移除临时文件"""
        tmp_path = path + Booter.BOOTER_TMP_SUFFIX
        if os.path.exists(tmp_path):
            os.remove(tmp_path)
    
    def load(self) -> Optional[bytes]:
        """加载数据"""
        # 如果文件不存在则先创建，然后打开

        # 文件已创建或已经存在，打开文件进行操作
        try:
            with open(self.file_path, 'r+b') as f:
                data = f.read(8)  # 读取8字节的long值
                return data if len(data) == 8 else None
        except Exception:
            return None
    
    def update(self, data: bytes) -> None:
        """更新数据"""
        if len(data) != 8:
            raise ValueError("Data must be 8 bytes long")
        value=Parser.parse_int(data)
        tmp_path = self.path + self.BOOTER_TMP_SUFFIX
        
        # 写入临时文件
        with open(tmp_path, 'wb') as f:
            f.write(data)
        
        # 原子性替换
        if os.name == 'nt':  # Windows
            if os.path.exists(self.file_path):
                os.remove(self.file_path)
            os.rename(tmp_path, self.file_path)
        else:  # Unix-like
            os.rename(tmp_path, self.file_path)
    
    def close(self) -> None:
        """关闭booter（清理资源）"""
        self._remove_bad_tmp(self.path)